/**
 * @description mainStore 主页面数据；主要提供给login，store，el-select使用
 * @author hzq
 * @create 2024-11-21 12:31:49
 */

import { defineStore } from 'pinia'
import arrayToTree from 'array-to-tree'
import { getEntireRole, getEntireDepartment, getEntireMenu } from '@/api/main'
import type { IRole, IDepartment, IMenu } from '@/api/types'

interface IMainState {
  /** 全部角色数据 */
  entireRoles: IRole[]
  /** 全部部门数据 */
  entireDepartments: IDepartment[]
  /** 全部菜单数据 */
  entireMenus: IMenu[]
}

const useMainStore = defineStore('main', {
  state: (): IMainState => ({
    entireRoles: [],
    entireDepartments: [],
    entireMenus: []
  }),

  actions: {
    /** 请求全部部门及角色及菜单数据 */
    async fetchEntireDataAction() {
      const roleResult = await getEntireRole()
      const departmentResult = await getEntireDepartment()
      const menuResult = await getEntireMenu()
      this.entireRoles = roleResult.data.list
      this.entireDepartments = departmentResult.data.list
      this.entireMenus = menuResult.data.list
    }
  },
  getters: {
    /** 全部菜单数据映射，方便el-select取值 */
    entireMenusTree(store) {
      const map = store.entireMenus.map((item) => {
        return {
          label: item.name,
          value: item._id,
          parentId: item.parentId
        }
      })
      return arrayToTree(map, {
        parentProperty: 'parentId',
        customID: 'value',
        childrenProperty: 'children'
      })
    },
    /** 全部角色数据映射，方便el-select取值 */
    entrieRolesMap(store) {
      return store.entireRoles.map((item) => {
        return {
          label: item.name,
          value: item._id
        }
      })
    },
    /** 全部部门数据映射，方便el-select取值 */
    entrieDepartmentsMap(store) {
      return store.entireDepartments.map((item) => {
        return {
          label: item.name,
          value: item._id
        }
      })
    }
  }
})

export default useMainStore
